import sys
import os
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QPushButton,
                             QHBoxLayout, QVBoxLayout, QListWidget, QSlider,
                             QFileDialog)
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtCore import Qt, QUrl, QTimer, QSize
from PyQt5.QtGui import QPixmap, QFont, QIcon


def resource_path(relative_path):
    """资源路径处理"""
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


class AnimePlayer(QWidget):
    def __init__(self):
        super().__init__()
        self.player = QMediaPlayer()
        self.playlist = []
        self.current_index = 0
        self.init_ui()
        self.init_player()

    def init_ui(self):
        """初始化蓝色主题界面"""
        self.setWindowIcon(QIcon(resource_path("resources/icon.ico")))
        self.setWindowTitle("月月音乐播放器")
        self.setGeometry(300, 300, 400, 600)
        self.setStyleSheet(self.load_stylesheet())

        # 主布局
        main_layout = QVBoxLayout()

        # 封面区域
        self.cover_label = QLabel(self)
        self.cover_label.setAlignment(Qt.AlignCenter)
        self.cover_label.setPixmap(QPixmap(resource_path("resources/cover.png")))
        main_layout.addWidget(self.cover_label)

        # 播放控制区域
        control_layout = QHBoxLayout()

        self.btn_prev = self.create_icon_button("prev")
        self.btn_play = self.create_icon_button("play")
        self.btn_next = self.create_icon_button("next")
        self.btn_open = self.create_icon_button("open")

        control_layout.addWidget(self.btn_prev)
        control_layout.addWidget(self.btn_play)
        control_layout.addWidget(self.btn_next)
        control_layout.addWidget(self.btn_open)

        # 进度条（蓝色主题）
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setStyleSheet("""
            QSlider::groove:horizontal {
                height: 8px;
                background: #87CEEB;
                border-radius: 4px;
            }
            QSlider::handle:horizontal {
                background: #4169E1;
                width: 16px;
                margin: -4px 0;
                border-radius: 8px;
            }
        """)

        # 播放列表（蓝色主题）
        self.list_widget = QListWidget()
        self.list_widget.setStyleSheet("""
            QListWidget {
                background: rgba(135,206,235, 0.3);
                font-size: 14px;
                color: white;
            }
            QListWidget::item:selected {
                background: #4169E1;
                color: white;
            }
        """)

        main_layout.addWidget(self.slider)
        main_layout.addLayout(control_layout)
        main_layout.addWidget(self.list_widget)
        self.setLayout(main_layout)

    def init_player(self):
        """初始化播放器组件"""
        self.player.setVolume(50)
        self.slider.sliderMoved.connect(self.set_position)
        self.player.durationChanged.connect(self.update_duration)
        self.player.positionChanged.connect(self.update_position)
        self.list_widget.itemDoubleClicked.connect(self.play_selected)

    def create_anime_button(self, text, name):
        """创建蓝色主题按钮"""
        btn = QPushButton(text)
        btn.setObjectName(name)
        btn.setFixedSize(60, 60)
        btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #4169E1, stop:1 #0000FF);
                border-radius: 30px;
                color: white;
                font-size: 24px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0000FF, stop:1 #4169E1);
            }
        """)
        btn.clicked.connect(self.on_button_click)
        return btn

    def load_stylesheet(self):
        """加载蓝色主题QSS"""
        return """
            QWidget {
                background: rgba(135,206,235, 0.1);
            }
            QLabel#cover_label {
                border: 2px solid #4169E1;
                border-radius: 15px;
            }
        """

    def on_button_click(self):
        """按钮点击事件处理:ml-citation{ref="5" data="citationList"}"""
        sender = self.sender()
        if sender.objectName() == "play":
            self.toggle_play()
        elif sender.objectName() == "prev":
            self.play_previous()
        elif sender.objectName() == "next":
            self.play_next()
        elif sender.objectName() == "open":
            self.load_music()

    def toggle_play(self):
        """播放/暂停切换:ml-citation{ref="5" data="citationList"}"""
        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/play.png")))
        else:
            self.player.play()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/pause.png")))

    def load_music(self):
        """加载音乐文件:ml-citation{ref="5" data="citationList"}"""
        folder = QFileDialog.getExistingDirectory(self, "选择音乐文件夹")
        if folder:
            self.playlist = [os.path.join(folder, f) for f in os.listdir(folder)
                             if f.endswith(('.mp3', '.wav', '.flac'))]
            self.list_widget.clear()
            self.list_widget.addItems([os.path.basename(f) for f in self.playlist])
            if self.playlist:
                self.play_music(0)

    def play_music(self, index):
        """播放指定索引的音乐:ml-citation{ref="5" data="citationList"}"""
        if 0 <= index < len(self.playlist):
            self.current_index = index
            media = QMediaContent(QUrl.fromLocalFile(self.playlist[index]))
            self.player.setMedia(media)
            self.player.play()
            self.btn_play.setIcon(QIcon(resource_path("resources/icons/pause.png")))

    def play_next(self):
        """播放下一首:ml-citation{ref="5" data="citationList"}"""
        if self.playlist:
            self.current_index = (self.current_index + 1) % len(self.playlist)
            self.play_music(self.current_index)

    def play_previous(self):
        """播放上一首:ml-citation{ref="5" data="citationList"}"""
        if self.playlist:
            self.current_index = (self.current_index - 1) % len(self.playlist)
            self.play_music(self.current_index)

    def set_position(self, position):
        """设置播放进度:ml-citation{ref="5" data="citationList"}"""
        self.player.setPosition(position)

    def update_duration(self, duration):
        """更新进度条长度:ml-citation{ref="5" data="citationList"}"""
        self.slider.setRange(0, duration)

    def update_position(self, position):
        """更新当前播放位置:ml-citation{ref="5" data="citationList"}"""
        self.slider.setValue(position)

    def play_selected(self, item):
        """双击播放列表项:ml-citation{ref="5" data="citationList"}"""
        index = self.list_widget.row(item)
        self.play_music(index)

    def create_icon_button(self, btn_type):
        """创建图标按钮"""
        btn = QPushButton()
        btn.setObjectName(btn_type)
        btn.setFixedSize(64, 64)

        # 设置图标样式
        icon_path = f"resources/icons/{btn_type}.png"
        btn.setIcon(QIcon(resource_path(icon_path)))
        btn.setIconSize(QSize(48, 48))

        # 按钮样式表
        btn.setStyleSheet("""
                        QPushButton {
                            background: transparent;
                            border: none;
                        }
                        QPushButton:hover {
                            background: rgba(255,105,180, 0.2);
                            border-radius: 32px;
                        }
                    """)
        btn.clicked.connect(self.on_button_click)
        return btn



if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setFont(QFont("Microsoft YaHei", 10))
    player = AnimePlayer()
    player.show()
    sys.exit(app.exec_())

# pyinstaller --noconsole --onefile --icon=resources/icon.ico --add-data "resources/icons;resources/;" --hidden-import PyQt5.QtMultimedia --hidden-import PyQt5.QtWidgets music_player.py

# pyinstaller --noconsole --onefile --icon=resources/icon.ico --add-data "resources/*;resources/;resources/icons" --hidden-import PyQt5.QtMultimedia --hidden-import PyQt5.QtWidgets music_player.py